package com.apes.framework.query.lib;

import com.apes.framework.jpa.TableMetadata;
import com.apestech.framework.dictionary.DataDictionary;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.sql.callback.SqlCallback;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.util.StringUtil;

import java.util.ArrayList;

/**
 * JAP模式下获取数据字典接口
 *
 * @author hup
 * @create 2018-06-11-19:19
 */
public class JPASqlCallBack extends StringUtil implements SqlCallback {

    private String exName="JPA";

    @Override
    public String getField(FromList fromtab, String fieldname) throws Exception {
        if(fromtab==null) return fieldname;
        String fname=fieldname;
        String[] flist=null;
        if(fieldname.indexOf(".")>=0){
            flist=fieldname.split("\\.");
            fname=flist[0];
        }
        String key=null;
        int len=fromtab.size();
        for(int i=0; i<len; i++){
            String tableName=fromtab.getTable(i);
            Table tab=fromtab.getDictTable(tableName);
            key=tab.getExName(exName, fname);
            if(key==null){
                key=updateDict(tab, tableName, fname);
                String key1=key;
                if(flist!=null){
                    int flen=flist.length;
                    for(int j=1; j<flen; j++){
                        fname=flist[j];
                        tableName=tab.getfTab(key1);
                        tab=fromtab.getDictTableAll(tab.getfTab(key1));
                        if(tab==null) throw new Exception("中间字段ID["+flist[j-1]+"]必须为关联字段");
                        key1=updateDict(tab, tableName, fname);
                        if(key1==null) throw new Exception("中间字段ID["+flist[j-1]+"]必须为关联字段");
                        key=key+"."+key1;
                    }
                }
            }
            if(key!=null) break;
        }
        if(key==null) key=fieldname;
        return key;
    }

    private String updateDict(Table tab, String tableName, String fname) throws Exception {
        String key=null;
        TableMetadata.Field field=TableMetadata.getFieldByName(tableName, fname);
        if(field!=null) {
            tab.setExName(exName, fname, field.getName());
            tab.setExType(exName, fname, field.getType());
            tab.setExSize(exName, fname, field.getLength());
            key=field.getField().toUpperCase();
            DataDictionary.updateTableCache(tableName, tab);
        }
        return key;
    }

    @Override
    public JSONObject toJSON(FromList tables, JSONObject map) throws Exception {
        int tlen=tables.size();
        for(int t=0; t<tlen; t++){
            String table=tables.getTable(t);
            if(table!=""){
                Table tab=tables.getDictTable(table);
                ArrayList<String> klist=map.getKeylist();
                int klen=klist.size();
                for(int k=0; k<klen; k++){
                    String key=klist.get(k);
                    Object idval=map.get(key);
                    if(idval==null){
                        map.remove(key);
                    } else {
                        if(tab.getField().get(key)!=null){
                            if(idval!=null){
                                if(tab.getfTab(key)!=null && key.indexOf("_")>=0){  //存在外键
                                    String ftab=key.substring(0, key.indexOf("_"));
                                    String fname=ftab+"_NAME";
                                    String name=map.getString(fname);
                                    if(name==null){
                                        name="";
                                    }
                                    JSONObject j=new JSONObject();
                                    j.put("id", idval);
                                    j.put("name", name);
                                    map.put(getJPAName(ftab), j);
                                    map.remove(fname);
                                } else {
                                    String jkey=getJPAName(key);
                                    map.put(jkey, map.get(key));
                                }
                                map.remove(key);
                            }
                        }
                    }

                }
            }
        }
        return map;
    }

    @Override
    public String getFieldName(FromList tables, String field) throws Exception {
        int len=tables.size();
        for(int i=0; i<len; i++){
            String tab=tables.getTable(i);
            TableMetadata.Field f=TableMetadata.getFieldByName(tab, field);
            if(f!=null){
                return f.getField();
            }
        }
        return field;
    }

    @Override
    public String getChildSelect(String key, String colName, String ftabName, Table ftab) throws Exception {
        String name=key+"_NAME";
        if(rightStr(key,3).equals("_ID")) {
            name = key.substring(0, key.length() - 3) + "_NAME";
            if ("MAS_ENUMERATION".equals(ftabName)) {
                return "(SELECT Z.DESCRIPTION FROM " + ftabName + " Z WHERE A." + key + "=Z." + colName + ") AS " + name;
            } else if ("CRM_CUSTOMER_CAR".equals(ftabName)) {
                return "(SELECT Z.PLATE_NUMBER FROM " + ftabName + " Z WHERE A." + key + "=Z." + colName + ") AS PLATE_NUMBER";
            } else if ("MAS_PARTY_ROLE".equals(ftabName)) {
                return "(SELECT Z2.NAME FROM MAS_PARTY_ROLE Z1, MAS_PARTY Z2 WHERE Z1.PARTY_ID=Z2.ID AND A." + key + "=Z1." + colName + ") AS " + name;
            } else if ("AUT_OPERATIONS".equals(ftabName)) {
                return null;
            }
        }
        return null;
    }

}
